<?php

namespace App\Utils\Traits;

use App\Utils\Annotation\ApiParam;
use App\Utils\Helper\ApiHelper;
use App\Utils\Helper\GetterHelper;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Trait ControllerTrait
 * @package App\Utils\Traits
 * @property ContainerInterface $container
 */
trait ControllerTrait {

    /**
     * 获取 doctrine.orm.entity_manager default
     * @return \Doctrine\ORM\EntityManager|mixed
     */
    public function getEntityManage () {
        return GetterHelper::getEntityManager();
    }

    /**
     * 获得声明中的参数
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function onlyDeclare (Request $request): array {
        $result = [];

        $parameters = ApiHelper::getInstance()->getParameters();
        if ($request->getMethod() === 'GET') {
            $params = $request->query->all();
        } else {
            $params = json_decode($request->getContent(), true);
        }
        foreach ($parameters as $parameter) {
            if ($parameter instanceof ApiParam) {
                if (isset($params[$parameter->name])) {
                    $result[$parameter->name] = $params[$parameter->name];
                } else if (!is_null($parameter->default)) {
                    switch ($parameter->type) {
                        case 'string':
                            $default = (string)$parameter->default;
                            break;
                        case 'boolean':
                            $default = (boolean)$parameter->default;
                            break;
                        case 'integer':
                            $default = (int)$parameter->default;
                            break;
                        case 'array':
                            $default = (array)$parameter->default;
                            break;
                        default:
                            $default = $parameter->default;
                    }
                    $result[$parameter->name] = $default;
                }
            }
        }

        return $result;
    }
}